<template>
  <XcForm
    ref="formView"
    v-model:visible="visible"
    :state="state"
    :closeReset="true"
    :title="title"
    :config="config"
    :values="formData"
    isDialog
    :colProps="6"
    :dialogWidth="600"
    :dialogHeight="300"
    dialogMaximize
    @open="init"
    @submit="submit">
  </XcForm>
</template>

<script lang="ts" setup>
import type { ColumnItem, XcFormInstance } from "@xc-components/xc-form/types";
import { ElMessage } from "element-plus";
import { computed, ref, type Ref } from "vue";
import type { UserItem } from "@/api/user/index.d";
import { addUser, updateUser } from "../../api/user/index";
import type { OptionItem } from "../../api/index.d";

defineOptions({
  name: "FormDialog"
});
const emits = defineEmits(["update"]);
const visible = defineModel<boolean>();
const props = withDefaults(defineProps<{ detail?: UserItem; roles?: OptionItem[] }>(), {
  detail: () => ({}) as UserItem,
  roles: () => [] as OptionItem[]
});
const title = computed(() => (props.detail?.id ? "编辑用户" : "新增用户"));
const state = ref<"loading" | "error" | "">("");
const formData = ref({}) as Ref<UserItem>;
const formView: Ref<XcFormInstance<UserItem> | null> = ref(null);
const config: ColumnItem<UserItem>[] = [
  { label: "用户名", prop: "name", required: true },
  { label: "账号", prop: "account", required: true },
  {
    label: "密码",
    prop: "password",
    inputType: "password",
    required: true,
    placeholder: "大小写字母+数字+特殊符号8位以上",
    rules: [
      {
        validator: (_, value: string, callback: (Error?: Error) => void) => {
          const pattrn = /^(?![A-Za-z0-9]+$)(?![a-z0-9\W]+$)(?![A-Za-z\W]+$)(?![A-Z0-9\W]+$)[a-zA-Z0-9\W]{8,}$/;
          if (value && !pattrn.test(value)) {
            callback(new Error("请输入正确的密码格式！"));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ]
  },
  {
    label: "确认密码",
    prop: "password2",
    inputType: "password",
    required: true,
    placeholder: "请再次输入密码",
    rules: [
      {
        validator: (_, value: string, callback: (Error?: Error) => void) => {
          const formVal = formView.value?.data;
          console.log(formVal);
          if (value !== formVal?.password) {
            callback(new Error("两次输入密码不一致"));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ]
  },
  { label: "角色", prop: "role", type: "select", options: [], required: true }
];
/**
 * @description: 初始化
 * @return {*}
 */
const init = async () => {
  const id = props.detail?.id;
  id && getInfo();
  formView.value?.update("role", "options", props.roles);
  formView.value?.update("password", "required", !id);
  formView.value?.update("password2", "required", !id);
  formView.value?.update("account", "disabled", !!id);
};

/**
 * @description: 详情
 * @param {*} isLoading
 * @return {*}
 */
const getInfo = async () => {
  formData.value = {} as UserItem;
  Object.entries(props.detail || {}).forEach(([key, value]) => {
    formData.value[key as keyof UserItem] = value as never;
  });
};

/**
 * @description: 保存
 * @param {*} value
 * @param {*} done
 * @return {*}
 */
const submit = async ({ value, done }: { value: any; done: (isClose?: boolean) => void }) => {
  console.log(value);
  try {
    const id = props.detail?.id;
    const api = id ? updateUser : addUser;
    await api({ user: { id: id || "", ...value, password2: undefined } });
    done?.();
    visible.value = false;
    ElMessage({ type: "success", message: id ? "修改成功" : "新增成功" });
    emits("update");
  } catch {
    done?.();
  }
};
</script>
<style lang="scss" scoped></style>
